<?php

class SiteController extends Controller {

    /**

     * Declares class-based actions.

     */
    
    public function actions() {

        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page

            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    /**

     * This is the default 'index' action that is invoked

     * when an action is not explicitly requested by users.

     */
    public function actionIndex() {

        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/main.php'
        // $model = new CalculadoraForm();


        $modelCalculo = CalculoCatastral::model()->with(array(
            'ValoresUnitariosTerrenosUrbanos' => array(
                'select' => 'barrio',
                'joinType' => 'INNER JOIN',
                'alias' => 'd'
            ),
        ));

        //$dataProvider = $modelCalculo->findAll();

        $this->render('admin', array('model' => $modelCalculo));
    }

    public function actionPdf() {

        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/main.php'
        // $model = new CalculadoraForm();


        $idCatrasto = Yii::app()->request->getQuery('id', 1);
        $command = Yii::app()->db;
        $db = $command->getPdoInstance();
        $sql = "SELECT a.*, b.barrio, c.nameClase, d.nombreForma, e.nivelPlanta, f.porche,g.materialMuro
                    FROM calculoCatastral a
                    INNER JOIN valoresUnitariosTerrenosUrbanos b on (a.idBarrio=b.id)
                    INNER JOIN clase c on (a.idClase=c.id)
                    INNER JOIN factorFormaEstructura d on (a.idFactorEstructura = d.id)
                    INNER JOIN factorNivelPlanta e on (a.idPlanta=e.id)
                    INNER JOIN garajes f on (a.idGaraje=f.id)
                    INNER JOIN materialMuro g on (a.materialMuro=g.id)
                 WHERE a.id=?";
        $sth = $db->prepare($sql);
        $sth->setFetchMode(PDO::FETCH_OBJ);
        $exist = $sth->execute(array($idCatrasto));
        $result = null;

        if ($exist && $sth->rowCount() > 0) {
            $result = $sth->fetch();
        }

        //print_r($result);
        # HTML2PDF has very similar syntax
        //echo $result['id'];
        $html2pdf = Yii::app()->ePdf->HTML2PDF();
        $html2pdf->WriteHTML($this->renderPartial('pdf', array('result' => $result), true));
        $html2pdf->Output();
    }

    public function actionDelete() {
        if (Yii::app()->request->isPostRequest) {
            if (isset($_GET['id']))
                CalculoCatastral::model()->findbyPk($_GET['id'])->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_POST['ajax']))
                $this->redirect(array('index'));
        }
        else
            throw new CHttpException(400, Yii::t('App', 'Invalid request. Please do not repeat this request again.'));
    }

    

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'data-grid') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionRegister() {
        $model = new CalculadoraForm();
        if (isset($_POST['CalculadoraForm'])) {
            $values = $_POST['CalculadoraForm'];
            $calculo = new CalculoCatastral();
            foreach ($values as $index => $value) {
                $value = str_replace(",", "", $value);
                switch ($index) {
                    case 'barrio':$calculo->idBarrio = $value;
                        break;
                    case 'direccion':$calculo->direccionTradicional = $value;
                        break;
                    case 'finca':$calculo->numRegistro = $value;
                        break;
                    case 'calidad':$calculo->idCalidad = $value;
                        break;
                    case 'clase':$calculo->idClase = $value;
                        break;
                    case 'factorFormaEstructura':$calculo->idFactorEstructura = $value;
                        break;
                    case 'factorNivelPlanta':$calculo->idPlanta = $value;
                        break;
                    case 'garaje':$calculo->idGaraje = $value;
                        break;
                    default :
                        $calculo->$index = $value;
                }
            }


            if ($calculo->save())
                $this->redirect(array('index'));
            //$this->redirect(array('view','id'=>$model->id));
        }

        $this->render('index', array('model' => $model));
    }

    /**

     * Displays the contact page

     */
    public function actionDatosBarrios() {

        $idBarrio = Yii::app()->request->getQuery('idBarrio', 0);

        $command = Yii::app()->db;

        $db = $command->getPdoInstance();

        $sql = "SELECT * FROM valoresUnitariosTerrenosUrbanos WHERE id=?";

        $sth = $db->prepare($sql);

        $sth->setFetchMode(PDO::FETCH_OBJ);

        $exist = $sth->execute(array($idBarrio));

        $result = null;

        if ($exist && $sth->rowCount() > 0) {

            $result = $sth->fetch();
        }



        header("Content-type: text/json");

        echo json_encode($result);

        exit();
    }

    public function actionFormaEstructura() {



        $idForma = Yii::app()->request->getQuery('idForma', 0);



        $command = Yii::app()->db;

        $db = $command->getPdoInstance();

        $sql = "SELECT * FROM factorFormaEstructura WHERE id=?";

        $sth = $db->prepare($sql);

        $sth->setFetchMode(PDO::FETCH_OBJ);

        $exist = $sth->execute(array($idForma));

        $result = null;

        if ($exist && $sth->rowCount() > 0) {

            $result = $sth->fetch();
        }



        header("Content-type: text/json");

        echo json_encode($result);

        exit();
    }

    public function actionGarage() {



        $idForma = Yii::app()->request->getQuery('idGarage', 0);



        $command = Yii::app()->db;

        $db = $command->getPdoInstance();

        $sql = "SELECT * FROM garajes WHERE id=?";

        $sth = $db->prepare($sql);

        $sth->setFetchMode(PDO::FETCH_OBJ);

        $exist = $sth->execute(array($idForma));

        $result = null;

        if ($exist && $sth->rowCount() > 0) {

            $result = $sth->fetch();
        }



        header("Content-type: text/json");

        echo json_encode($result);

        exit();
    }

    public function actionMuros() {



        $altura = Yii::app()->request->getQuery('altura', 0);
        $idMaterial = Yii::app()->request->getQuery('idMaterial', 0);



        $command = Yii::app()->db;

        $db = $command->getPdoInstance();

        $sql = "SELECT * FROM detalleAdicionalesResidenciales WHERE altura=? AND materialMuroId=?";

        $sth = $db->prepare($sql);

        $sth->setFetchMode(PDO::FETCH_OBJ);

        $exist = $sth->execute(array($altura, $idMaterial));

        $result = null;

        if ($exist && $sth->rowCount() > 0) {

            $result = $sth->fetch();
        }



        header("Content-type: text/json");

        echo json_encode($result);

        exit();
    }

    public function actionNivelPlanta() {



        $idNivel = Yii::app()->request->getQuery('idNivel', 0);



        $command = Yii::app()->db;

        $db = $command->getPdoInstance();

        $sql = "SELECT * FROM factorNivelPlanta WHERE id=?";

        $sth = $db->prepare($sql);

        $sth->setFetchMode(PDO::FETCH_OBJ);

        $exist = $sth->execute(array($idNivel));

        $result = null;

        if ($exist && $sth->rowCount() > 0) {

            $result = $sth->fetch();
        }



        header("Content-type: text/json");

        echo json_encode($result);

        exit();
    }

    public function actionCostoUnitarioEstructura() {



        $calidad = Yii::app()->request->getQuery('calidad', 0);

        $claseId = Yii::app()->request->getQuery('claseId', 0);



        $command = Yii::app()->db;

        $db = $command->getPdoInstance();



        $sql = "SELECT * FROM costoUnitarioEstructura WHERE calidad=? AND claseId=?";

        $sth = $db->prepare($sql);

        $sth->setFetchMode(PDO::FETCH_OBJ);

        $exist = $sth->execute(array($calidad, $claseId));

        $result = null;

        if ($exist && $sth->rowCount() > 0) {

            $result = $sth->fetch();
        }



        header("Content-type: text/json");

        echo json_encode($result);

        exit();
    }

    public function actionVidaProbable() {



        $calidad = Yii::app()->request->getQuery('calidad', 0);

        $claseId = Yii::app()->request->getQuery('claseId', 0);



        $command = Yii::app()->db;

        $db = $command->getPdoInstance();



        $sql = "SELECT * FROM vidaProbable WHERE calidad=? AND claseId=?";

        $sth = $db->prepare($sql);

        $sth->setFetchMode(PDO::FETCH_OBJ);

        $exist = $sth->execute(array($calidad, $claseId));

        $result = null;

        if ($exist && $sth->rowCount() > 0) {

            $result = $sth->fetch();
        }



        header("Content-type: text/json");

        echo json_encode($result);

        exit();
    }

    public function actionDepreciacion() {



        $vida = Yii::app()->request->getQuery('vida', 0);

        $edad = Yii::app()->request->getQuery('edad', 0);



        $command = Yii::app()->db;

        $db = $command->getPdoInstance();



        $sql = "SELECT * FROM depreciacionNormal WHERE edad=? AND vidaProbable=?";

        $sth = $db->prepare($sql);

        $sth->setFetchMode(PDO::FETCH_OBJ);

        $exist = $sth->execute(array($edad, $vida));

        $result = null;

        if ($exist && $sth->rowCount() > 0) {

            $result = $sth->fetch();
        }



        header("Content-type: text/json");

        echo json_encode($result);

        exit();
    }

    public function actionFactorModificacionxArea() {



        $calidad = Yii::app()->request->getQuery('calidad', 0);

        $area = Yii::app()->request->getQuery('area', 0);



        $command = Yii::app()->db;

        $db = $command->getPdoInstance();



        $sql = "SELECT * FROM factorModificacionxArea WHERE calidad=? AND ((InicioRango<=? AND FinRango>?) OR (InicioRango<=? AND FinRango IS NULL))";

        $sth = $db->prepare($sql);

        $sth->setFetchMode(PDO::FETCH_OBJ);

        $exist = $sth->execute(array($calidad, $area, $area, $area));

        $result = null;

        if ($exist && $sth->rowCount() > 0) {

            $result = $sth->fetch();
        }



        header("Content-type: text/json");

        echo json_encode($result);

        exit();
    }

    public function actionPorchesBalcones() {



        $ckporche = Yii::app()->request->getQuery('ckporche', array());



        $params = array('techo' => 0, 'piso' => 0, 'baranda' => 0, 'cieloraso' => 0, 'estructuraEdificioPrincipal' => 0, 'voladizo' => 0, 'balcones' => 0);

        foreach ($ckporche as $ck) {

            $ck = trim(str_replace("CalculadoraForm_", "", $ck));

            $params[$ck] = 1;
        }

        //Verificar condiciones absolutas

        if ($params['balcones'] == 1) {

            $params['voladizo'] = 1;
        }

        if ($params['voladizo'] == 1) {

            $params['estructuraEdificioPrincipal'] = 1;
        }

        if ($params['estructuraEdificioPrincipal'] == 1) {

            $params['techo'] = 1;

            $params['piso'] = 1;

            $params['baranda'] = 1;

            $params['cieloraso'] = 1;
        }



        $condition = array();

        foreach ($params as $field => $value) {

            $condition[] = $field . "=" . $value;
        }





        $command = Yii::app()->db;

        $db = $command->getPdoInstance();



        $sql = "SELECT * FROM porchesBalcones ";

        if (count($condition) > 0) {

            $sql.= "WHERE " . join(" AND ", $condition);
        }

        $sth = $db->prepare($sql);

        $sth->setFetchMode(PDO::FETCH_OBJ);

        $exist = $sth->execute();

        $result = null;

        if ($exist && $sth->rowCount() > 0) {

            $result = $sth->fetch();
        }



        header("Content-type: text/json");

        echo json_encode($result);

        exit();
    }

    /**

     * This is the action to handle external exceptions.

     */
    public function actionError() {

        if ($error = Yii::app()->errorHandler->error) {

            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**

     * Displays the contact page

     */
    public function actionContact() {

        $model = new ContactForm;

        if (isset($_POST['ContactForm'])) {

            $model->attributes = $_POST['ContactForm'];

            if ($model->validate()) {

                $headers = "From: {$model->email}\r\nReply-To: {$model->email}";

                mail(Yii::app()->params['adminEmail'], $model->subject, $model->body, $headers);

                Yii::app()->user->setFlash('contact', 'Thank you for contacting us. We will respond to you as soon as possible.');

                $this->refresh();
            }
        }

        $this->render('contact', array('model' => $model));
    }

    /**

     * Displays the login page

     */
    public function actionLogin() {

        $model = new LoginForm;



        // if it is ajax validation request

        if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {

            echo CActiveForm::validate($model);

            Yii::app()->end();
        }



        // collect user input data

        if (isset($_POST['LoginForm'])) {

            $model->attributes = $_POST['LoginForm'];

            // validate user input and redirect to the previous page if valid

            if ($model->validate() && $model->login())
                $this->redirect(Yii::app()->user->returnUrl);
        }

        // display the login form

        $this->render('login', array('model' => $model));
    }

    /**

     * Logs out the current user and redirect to homepage.

     */
    public function actionLogout() {

        Yii::app()->user->logout();

        $this->redirect(Yii::app()->homeUrl);
    }

}